﻿using IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using static WMS.Controllers.WhInboundController;

namespace WMS.Controllers
{
    public class WhTransferController : Controller
    {
        private readonly IDictService _dictService;
        private readonly IWhTransferService _whTransferService;
        private readonly IWebHostEnvironment _webHostEnv; // 新增：用于获取服务器路径

        public WhTransferController(IDictService dictService, IWhTransferService whTransferService, IWebHostEnvironment webHostEnv)
        {
            _dictService = dictService;
            _whTransferService = whTransferService;
            _webHostEnv = webHostEnv;
        }


        public async Task<ActionResult> Index()
        {
            //获取调拨单出入库状态字典数据
            var dictTypeForTransfreOutIn = await _dictService.GetDictTypeAsync("sys_transfer_out_in_status");
            if (dictTypeForTransfreOutIn != null)
            {
                var stockInTypeList = await _dictService.GetDictDataListAsync(dictTypeForTransfreOutIn.DictTypeId);
                ViewBag.StockInTypeList = stockInTypeList;
            }
            //获取调拨单状态字典数据
            var dictTypeForTransferOrderStatus = await _dictService.GetDictTypeAsync("sys_transfer_order_status");
            if (dictTypeForTransferOrderStatus != null)
            {
                var orderStatusList = await _dictService.GetDictDataListAsync(dictTypeForTransferOrderStatus.DictTypeId);
                ViewBag.OrderStatusList = orderStatusList;
            }
            //获取调拨类型字典数据
            var dictTypeForTransferType = await _dictService.GetDictTypeAsync("sys_transfer_type");
            if (dictTypeForTransferType != null)
            {
                var transferTypeList = await _dictService.GetDictDataListAsync(dictTypeForTransferType.DictTypeId);
                ViewBag.TransferTypeList = transferTypeList;
            }
            return View();
        }

        //---------------------------------------------------查询开始-----------------------------------------------------------
        /// <summary>
        /// 获取全部调拨单信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllTransferInfo()
        {
            var result = _whTransferService.GetAllTransferOrderInfo();
            return Json(result);
        }

        /// <summary>
        /// 多条件查询调拨单信息
        /// </summary>
        /// <param name="swtwsm"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetTransferWithSth([FromBody] SelectWhTransferWithSthModel swtwsm)
        {
            var result = await _whTransferService.SelectTransferOrderWithSth(swtwsm);
            return Json(result);
        }

        //---------------------------------------------------查询结束-----------------------------------------------------------

        public async Task<ActionResult> AddIndex()
        {
            var dictTypeForTransfreType = await _dictService.GetDictTypeAsync("sys_transfer_type");
            if (dictTypeForTransfreType != null)
            {
                var stockInTypeList = await _dictService.GetDictDataListAsync(dictTypeForTransfreType.DictTypeId);
                ViewBag.StockInTypeList = stockInTypeList;
            }
            return View();
        }

        /// <summary>
        /// 根据调出仓库ID和调入仓库ID获取调拨商品信息
        /// </summary>
        /// <param name="outStockId"></param>
        /// <param name="inStockId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetTranceferInfo(long outStockId, long inStockId)
        {
            var result = await _whTransferService.GetTransferGoodsInfo(outStockId, inStockId);
            return Json(result);
        }

        /// <summary>
        /// 根据库位ID、仓库ID和商品ID查询该库位该商品的库存数量
        /// </summary>
        /// <param name="locationId"></param>
        /// <param name="warehouseId"></param>
        /// <param name="goodsId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetAvailableInventoryQty(long locationId,long warehouseId,long goodsId)
        {
            var result = await _whTransferService.FindLocationQuantity(locationId, warehouseId, goodsId);
            return Json(result);
        }


        /// <summary>
        /// 添加调拨单、明细和附件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddTransferAndDetailWithAttachment([FromBody] TransferRequest request)
        {
            var result = 0;
            try
            {
                result = await _whTransferService.AddWhTransferOrderInfo(request.wtmwm, request.detailList, request.attachmentList);
            }
            catch (Exception)
            {
                throw;
            }
            return Json(result);
        }

        public class TransferRequest
        {
            public WhTransferModelWithMain wtmwm { get; set; }
            public List<WhTransferModelWithDetail> detailList { get; set; }
            public List<SysAttachmentDTO>? attachmentList { get; set; }
        }

        //-----------------------------------------------------审核----------------------------------------------------------------

        /// <summary>
        /// 审核调拨单
        /// </summary>
        /// <param name="am"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AuditeTransfer([FromBody] AuditerModel am)
        {
            var result = 0;
            try
            {
                result = _whTransferService.AuditeTransferOrder(am);
            }
            catch (Exception)
            {
                throw;
            }
            return Json(result);
        }


        //-----------------------------------------------------审核结束----------------------------------------------------------------

        //------------------------------------------------------附件---------------------------------------------------------------
        /// <summary>
        /// 附件上传（选择文件时调用）
        /// </summary>
        /// <param name="file">前端上传的单个文件</param>
        /// <returns>文件唯一标识、名称、大小等信息</returns>
        [HttpPost]
        public async Task<IActionResult> UploadAttachment(IFormFile file)
        {
            // 1. 校验文件合法性（格式、大小）
            if (file == null || file.Length == 0)
            {
                return Json(new { success = false, message = "请选择有效的文件" });
            }

            var allowedExtensions = new[] { ".doc", ".docx", ".pdf", ".rar", ".zip" };
            var fileExtension = Path.GetExtension(file.FileName).ToLower();
            if (!allowedExtensions.Contains(fileExtension))
            {
                return Json(new { success = false, message = "仅支持 doc、docx、pdf、rar、zip 格式" });
            }

            // 单个文件最大200MB（与前端提示一致）
            var maxFileSize = 200 * 1024 * 1024; // 200MB
            if (file.Length > maxFileSize)
            {
                return Json(new { success = false, message = "单个文件大小不能超过200MB" });
            }

            // 2. 定义服务器保存路径（建议放在 wwwroot 下，方便管理）
            var uploadDir = Path.Combine(_webHostEnv.WebRootPath, "uploads", "wh-transfer");
            // 若目录不存在，自动创建
            if (!Directory.Exists(uploadDir))
            {
                Directory.CreateDirectory(uploadDir);
            }

            // 3. 生成唯一文件名（避免重复覆盖，用 GUID 命名）
            var uniqueFileName = $"{Guid.NewGuid()}{fileExtension}"; // 例：550e8400-e29b-41d4-a716-446655440000.pdf
            var savePath = Path.Combine(uploadDir, uniqueFileName);

            // 4. 保存文件到服务器
            using (var stream = new FileStream(savePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            // 5. 生成文件唯一标识（fileId，建议用 GUID 或数据库自增ID，此处用文件名简化）
            var fileId = uniqueFileName; // 实际项目可存入数据库生成自增ID，此处暂用唯一文件名作为标识

            // 6. 返回结果给前端（前端需存储 fileId，用于后续删除）
            return Json(new
            {
                success = true,
                data = new
                {
                    fileId = fileId,          // 唯一标识，删除时需传此值
                    fileName = file.FileName, // 原始文件名（用于前端显示）
                    fileSize = file.Length,   // 文件大小（字节）
                    savePath = savePath       // 服务器保存路径（可选，用于后续关联入库单）
                },
                message = "文件上传成功"
            });
        }

        /// <summary>
        /// 附件删除（点击移除时调用）
        /// </summary>
        /// <param name="fileId">上传时返回的文件唯一标识</param>
        /// <returns>删除结果</returns>
        [HttpPost]
        public IActionResult DeleteAttachment([FromBody] DeleteAttachmentRequest request)
        {
            // 1. 校验 fileId
            if (string.IsNullOrEmpty(request.FileId))
            {
                return Json(new { success = false, message = "文件标识不能为空" });
            }

            // 2. 拼接服务器文件路径（与上传时的路径一致）
            var uploadDir = Path.Combine(_webHostEnv.WebRootPath, "uploads", "wh-inbound");
            var filePath = Path.Combine(uploadDir, request.FileId);

            // 3. 检查文件是否存在，存在则删除
            if (System.IO.File.Exists(filePath))
            {
                try
                {
                    System.IO.File.Delete(filePath);
                }
                catch (Exception ex)
                {
                    return Json(new { success = false, message = $"文件删除失败：{ex.Message}" });
                }
            }
            else
            {
                return Json(new { success = false, message = "文件不存在，无需删除" });
            }

            // 4. （可选）删除数据库中该文件的临时关联信息（如暂存的 fileId 与入库单草稿的关联）
            // 此处需调用 Service 层方法，删除临时表中的记录，示例：
            // await _whInboundService.DeleteTempAttachment(request.FileId);

            // 5. 返回删除结果
            return Json(new { success = true, message = "文件删除成功" });
        }

        //------------------------------------------------------附件结束---------------------------------------------------------------

        //辅助方法------------------------------------------------------------------------------------------

        // 新增：删除附件的请求参数类（接收前端传递的 fileId）
        public class DeleteAttachmentRequest
        {
            public string FileId { get; set; }
        }

        /// <summary>
        /// 封装：根据 fileId 删除服务器上的附件
        /// </summary>
        /// <param name="fileId">附件唯一标识</param>
        /// <returns>是否删除成功</returns>
        private bool DeleteAttachmentByFileId(string fileId)
        {
            var uploadDir = Path.Combine(_webHostEnv.WebRootPath, "uploads", "wh-inbound");
            var filePath = Path.Combine(uploadDir, fileId);

            if (System.IO.File.Exists(filePath))
            {
                try
                {
                    System.IO.File.Delete(filePath);
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"删除附件失败：{ex.Message}");
                    return false;
                }
            }
            return true; // 文件不存在时，视为“已删除”
        }

        /// <summary>
        /// 回滚：删除已上传的附件
        /// </summary>
        /// <param name="attachmentFileIds">已上传的附件 ID 列表</param>
        private void RollbackAttachments(List<string>? attachmentFileIds)
        {
            if (attachmentFileIds == null || !attachmentFileIds.Any()) return;

            foreach (var fileId in attachmentFileIds)
            {
                DeleteAttachmentByFileId(fileId);
            }
        }

        /// <summary>
        /// 按服务器路径删除附件（用于提交失败回滚）
        /// </summary>
        /// <param name="filePaths">附件在服务器的完整路径列表</param>
        /// <returns>删除结果</returns>
        [HttpPost]
        public IActionResult DeleteAttachmentByPath([FromBody] List<string> filePaths)
        {
            if (filePaths == null || !filePaths.Any())
            {
                return Json(new { success = true, message = "无附件需删除" });
            }

            int deletedCount = 0;
            foreach (var path in filePaths)
            {
                // 校验路径合法性（避免跨目录删除，仅允许删除uploads/wh-inbound下的文件）
                if (string.IsNullOrEmpty(path) || !path.Contains(Path.Combine("uploads", "wh-inbound")))
                {
                    continue;
                }

                if (System.IO.File.Exists(path))
                {
                    try
                    {
                        System.IO.File.Delete(path);
                        deletedCount++;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"删除附件失败（路径：{path}）：{ex.Message}");
                    }
                }
            }

            return Json(new
            {
                success = true,
                message = $"共需删除{filePaths.Count}个附件，成功删除{deletedCount}个"
            });
        }
    }
}
